<!-- 角色模块主页面 -->
<template>
  <div class="content">
    <el-form class="searchForm">
      <el-form-item label="角色管理" />
      <el-form-item>
        <el-input id="search" v-model="searchRoleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button id="btnQuery" type="primary" @click="searchRole">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button id="btnAdd" type="primary" icon="el-icon-plus" @click="addRole">增加</el-button>
    <el-button type="danger" icon="el-icon-delete" @click="deleteRole">删除</el-button>
    <el-button type="primary" icon="el-icon-video-play" @click="roleAssign('RESOURCE')">资源分配</el-button>
    <el-button type="primary" icon="el-icon-user-solid" @click="roleAssign('USER')">用户分配</el-button>
    <el-button type="primary" icon="el-icon-user-solid" @click="roleAssign('COMPANY')">公司分配</el-button>
    <el-button type="primary" icon="el-icon-refresh" @click="operateRoleSuccess">刷新</el-button>
    <Table
      ref="roleTable"
      @operateRoleSuccess="operateRoleSuccess"
      @copyRole="copyRole($event)"
      @editRole="editRole($event)"
      @viewPermission="viewPermission($event)"
    />
    <DialogForm
      ref="roleDialogForm"
      :is-dialog-form-show="isDialogFormShow"
      :operate-type="operateType"
      @closeDialog="closeDialog"
      @operateRoleSuccess="operateRoleSuccess"
    />
    <DialogAssignUserVue
      ref="roleDialogAssignUser"
      :is-dialog-assign-user-show="isDialogAssignUserShow"
      @closeDialog="closeDialog"
      @operateRoleSuccess="operateRoleSuccess"
    />
    <DialogAssignCompanyVue
      ref="roleDialogAssignCompany"
      :is-dialog-assign-company-show="isDialogAssignCompanyShow"
      @closeDialog="closeDialog"
      @operateRoleSuccess="operateRoleSuccess"
    />
    <BossSoftTree
      :title="dialogAssignResourceTitle"
      :data="resourceTree"
      :type="resourceTreeType"
      :data-chosen="resourceTreeSelection"
      :visible="isDialogAssignResourceShow"
      @close="closeDialog"
      @confirm="assignResourceToRole($event)"
    />
  </div>
</template>

<script>
import {
  batchRemove,
  assignResource
} from '@/api/right/role'
import { treeQuery } from '@/api/right/resource'
import Table from './table.vue'
import DialogForm from './dialogForm.vue'
import DialogAssignUserVue from './dialogAssignUser.vue'
import DialogAssignCompanyVue from './dialogAssignCompany.vue'
import BossSoftTree from '@/components/SD365UI/BossSoftTree.vue'

export default {
  name: 'Role',
  components: {
    Table,
    DialogForm,
    DialogAssignUserVue,
    DialogAssignCompanyVue,
    BossSoftTree
  },
  data() {
    return {
      // 搜索时输入的角色名
      searchRoleName: '',
      // 是否展示增加、编辑和复制角色弹窗
      isDialogFormShow: false,
      // 操作类型
      operateType: '',
      // 是否展示用户分配弹窗
      isDialogAssignUserShow: false,
      // 是否展示公司分配弹窗
      isDialogAssignCompanyShow: false,
      // 是否展示资源分配弹窗
      isDialogAssignResourceShow: false,
      // 资源树
      resourceTree: [],
      // 被选中的资源树
      resourceTreeSelection: [],
      // 资源树类型
      resourceTreeType: 'VIEW',
      // 资源分配弹窗标题
      dialogAssignResourceTitle: ''
    }
  },
  methods: {
    // 查询角色
    searchRole() {
      this.$refs.roleTable.$emit('searchRole', this.searchRoleName)
    },
    /**
     * 添加角色
     */
    addRole() {
      this.operateType = 'ADD'
      this.isDialogFormShow = true
    },
    /**
     * 删除角色
     */
    deleteRole() {
      // 如果未选中角色数据，则报错
      if (!this.$refs.roleTable.roleDataSelection ||
      this.$refs.roleTable.roleDataSelection.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }

      this.$confirm('确定删除吗？')
        .then(async() => {
          // 将数据改成接口对应的格式
          const userVOS = []
          this.$refs.roleTable.roleDataSelection.map(item => {
            userVOS.push({ id: item.id, version: item.version })
          })

          // 调用接口
          try {
            let res = await batchRemove(userVOS)
            if (res) {
              this.$message.success('删除成功')
              this.operateRoleSuccess()
            } else {
              this.$message.error('删除失败')
            }
          } catch {
            this.$message.error('网络错误')
          }
        })
        .catch(() => {})
    },
    /**
     * 复制角色
     * @param {*} row 角色数据
     */
    copyRole(row) {
      if (!row || row.length > 1) {
        this.$message.error('请选择一条数据')
        return
      }

      this.operateType = 'COPY'
      this.$refs.roleDialogForm.$emit('updateRoleFrom', row)
      this.isDialogFormShow = true
    },
    /**
     * 编辑角色
     * @param {*} row 角色数据
     */
    editRole(row) {
      if (!row || row.length > 1) {
        this.$message.error('请选择一条数据')
        return
      }
      this.operateType = 'EDIT'
      this.$refs.roleDialogForm.$emit('updateRoleFrom', row)
      this.isDialogFormShow = true
    },
    /**
     * 查看角色权限
     * @param {*} row 角色数据
     */
    async viewPermission(row) {
      try {
        let res1 = await treeQuery({ pageSize: 1000 })
        let res2 = await treeQuery({ roleId: row.id, pageSize: 1000 })
        if (res1 && res2) {
          this.resourceTree = res1.data
          this.resourceTreeSelection = res2.data
          this.resourceTreeType = 'VIEW'
          this.dialogAssignResourceTitle = '资源分配:'
          this.isDialogAssignResourceShow = true
        } else {
          this.$message.error('资源获取失败')
        }
      } catch {
        this.$message.error('网络错误')
      }
    },
    /**
     * 角色分配资源，用户，公司
     * @param {*} type 分配类型 USER RESOURCE COMPANY
     */
    async roleAssign(type) {
      // 如果未选中角色数据，则报错
      if (!this.$refs.roleTable.roleDataSelection ||
      this.$refs.roleTable.roleDataSelection.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }

      // 根据类型不同打开不同弹窗
      if (type === 'RESOURCE') {
        try {
          const roleId = this.$refs.roleTable.roleDataSelection[0].id
          let res1 = await treeQuery({ pageSize: 1000 })
          let res2 = await treeQuery({ roleId, pageSize: 1000 })
          if (res1 && res2) {
            this.resourceTree = res1.data
            this.resourceTreeSelection = res2.data
            this.resourceTreeType = 'ASSIGN'
            this.dialogAssignResourceTitle = '资源分配:'
            this.isDialogAssignResourceShow = true
          } else {
            this.$message.error('资源获取失败')
          }
        } catch {
          this.$message.error('网络错误')
        }
      } else if (type === 'USER') {
        this.$refs.roleDialogAssignUser.$emit('getUser', this.$refs.roleTable.roleDataSelection)
        this.isDialogAssignUserShow = true
      } else if (type === 'COMPANY') {
        this.$refs.roleDialogAssignCompany.$emit('getCompany', this.$refs.roleTable.roleDataSelection)
        this.isDialogAssignCompanyShow = true
      }
    },
    /**
     * 分配资源
     * @param {*} nodes 被选中的角色
     */
    async assignResourceToRole(nodes) {
      // 获取选中和半选中的资源
      let checkedNodes = nodes[0]
      let halfCheckedNodes = nodes[1]
      if (checkedNodes.length === 0) {
        this.$message.error('至少选择一个资源')
        return
      }
      let roleIds = []
      let resourceIds = []
      // 将角色列表改为接口对应的格式
      this.$refs.roleTable.roleDataSelection.map(item => {
        roleIds.push(item.id)
      })
      // 将资源列表改为接口对应的格式
      checkedNodes.map(item => {
        resourceIds.push(item.id)
      })
      halfCheckedNodes.map(item => {
        resourceIds.push(item.id)
      })
      // 调用接口
      try {
        let res = await assignResource({ roleIds, resourceIds })
        if (res) {
          this.$message.success('资源分配成功')
          this.closeDialog()
        } else {
          this.$message.error('资源分配失败')
        }
      } catch {
        this.$message.error('网络错误')
      }
    },
    /**
     * 操作角色成功
     */
    operateRoleSuccess() {
      this.$refs.roleTable.$emit('getRole')
    },
    /**
     * 关闭所有弹窗,重置数据
     */
    closeDialog() {
      this.operateType = ''
      this.resourceTree = []
      this.resourceTreeSelection = []
      this.resourceTreeType = 'VIEW'
      this.dialogAssignResourceTitle = ''
      this.isDialogFormShow = false
      this.isDialogAssignUserShow = false
      this.isDialogAssignCompanyShow = false
      this.isDialogAssignResourceShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  padding: 20px 45px;
  .searchForm{
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  #btnQuery{
    margin-left: 15px;
  }
}
</style>
